<?php
/**
 * Magento Enterprise Edition
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Magento Enterprise Edition End User License Agreement
 * that is bundled with this package in the file LICENSE_EE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.magento.com/license/enterprise-edition
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magento.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magento.com for more information.
 *
 * @category    Mage
 * @package     Mage_Adminhtml
 * @copyright Copyright (c) 2006-2015 X.commerce, Inc. (http://www.magento.com)
 * @license http://www.magento.com/license/enterprise-edition
 */

/**
 * Adminhtml customer grid block
 *
 * @category   Mage
 * @package    Mage_Adminhtml
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Silk_Zgb_Block_Adminhtml_Audit_Grid extends Mage_Adminhtml_Block_Widget_Grid
{

    public function __construct()
    {
        parent::__construct();
        $this->setId('productGrid');
        $this->setDefaultSort('entity_id');
        $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
        $this->setUseAjax(true);
        $this->setVarNameFilter('product_filter');

    }

    protected function _getStore()
    {
        $storeId = (int) $this->getRequest()->getParam('store', 0);
        return Mage::app()->getStore($storeId);
    }

    protected function _prepareCollection()
    {
        /* <<< AITOC CODE */
        $store = $this->_getStore(); 
        $iWebsiteId = $store->getWebsiteId(); 
        /* >>> AITOC CODE END */
        if (!$iWebsiteId)
        {
            $iWebsiteId = Mage::helper('aitquantitymanager')->getHiddenWebsiteId();
        }
        $collection = Mage::getModel('catalog/product')->getCollection()
            ->addAttributeToSelect('sku')
            ->addAttributeToSelect('name')
            ->addAttributeToSelect('attribute_set_id')
            ->addAttributeToSelect('type_id')->joinField('qty',
//              'cataloginventory/stock_staus', // +++ AITOC comment
                'aitquantitymanager/stock_item', // +++AITOC code
//              'aitquantitymanager/stock_status', // +++AITOC comment
                'qty',
                'product_id=entity_id',
//              '{{table}}.stock_id=1',// +++AITOC comment
                '{{table}}.stock_id=1 AND {{table}}.website_id = ' . $iWebsiteId, // +++AITOC code
                'left');

        // if (Mage::helper('catalog')->isModuleEnabled('Mage_CatalogInventory')) {
        //     $collection->joinField('qty',
        //         'cataloginventory/stock_item',
        //         'qty',
        //         'product_id=entity_id',
        //         '{{table}}.stock_id=1',
        //         'left');
        // }
        if ($store->getId()) {
            //$collection->setStoreId($store->getId());
            $adminStore = Mage_Core_Model_App::ADMIN_STORE_ID;
            $collection->addStoreFilter($store);
            $collection->joinAttribute(
                'name',
                'catalog_product/name',
                'entity_id',
                null,
                'inner',
                $adminStore
            );
            $collection->joinAttribute(
                'custom_name',
                'catalog_product/name',
                'entity_id',
                null,
                'inner',
                $store->getId()
            );
            $collection->joinAttribute(
                'status',
                'catalog_product/status',
                'entity_id',
                null,
                'inner',
                $store->getId()
            );
            $collection->joinAttribute(
                'status_at',
                'catalog_product/status_at',
                'entity_id',
                null,
                'left',
                $store->getId()
            );
            $collection->joinAttribute(
                'visibility',
                'catalog_product/visibility',
                'entity_id',
                null,
                'inner',
                $store->getId()
            );
            $collection->joinAttribute(
                'dealer_id',
                'catalog_product/dealer_id',
                'entity_id',
                null,
                'inner',
                $store->getId()
            );

            $collection->joinAttribute(
                'price',
                'catalog_product/price',
                'entity_id',
                null,
                'left',
                $store->getId()
            );
        }
        else {
            $collection->addAttributeToSelect('price');
            $collection->joinAttribute('status', 'catalog_product/status', 'entity_id', null, 'inner');
            $collection->joinAttribute('visibility', 'catalog_product/visibility', 'entity_id', null, 'inner');
        }
        //$collection->addAttributeToFilter('status',array('eq'=>2));
        //$collection->distinct(true);
        $collection->getSelect()->group('e.entity_id');
        //echo $collection->getSelect();
        $this->setCollection($collection);
        
        parent::_prepareCollection();
        $this->getCollection()->addWebsiteNamesToResult();
        return $this;
    }

    protected function _addColumnFilterToCollection($column)
    {
        if ($this->getCollection()) {
            if ($column->getId() == 'websites') {
                $this->getCollection()->joinField('websites',
                    'catalog/product_website',
                    'website_id',
                    'product_id=entity_id',
                    null,
                    'left');
            }
        }
        return parent::_addColumnFilterToCollection($column);
    }

    protected function _prepareColumns()
    {
        $zgb = Mage::helper('zgb');

        $this->addColumn('entity_id',
            array(
                'header'=> Mage::helper('catalog')->__('ID'),
                'width' => '50px',
                'type'  => 'number',
                'index' => 'entity_id',
        ));
        
        $this->addColumn('img',
            array(
                'header'=> Mage::helper('catalog')->__('产品缩略图'),
                'index' => 'entity_id',
                'renderer' => 'Silk_Zgb_Block_Renderer_Thumbnail',
                'width' => '80px'

        ));

        $store = $this->_getStore();
        if ($store->getId()) {
            $this->addColumn('custom_name',
                array(
                    'header'=> Mage::helper('catalog')->__('Name in %s', $store->getName()),
                    'index' => 'custom_name',
            ));
        }
        else
        {
            $this->addColumn('name',
                array(
                    'header'=> Mage::helper('catalog')->__('Name'),
                    'index' => 'name',
            ));
        }

        // $this->addColumn('type',
        //     array(
        //         'header'=> Mage::helper('catalog')->__('Type'),
        //         'width' => '60px',
        //         'index' => 'type_id',
        //         'type'  => 'options',
        //         'options' => Mage::getSingleton('catalog/product_type')->getOptionArray(),
        // ));

        // $sets = Mage::getResourceModel('eav/entity_attribute_set_collection')
        //     ->setEntityTypeFilter(Mage::getModel('catalog/product')->getResource()->getTypeId())
        //     ->load()
        //     ->toOptionHash();

        // $this->addColumn('set_name',
        //     array(
        //         'header'=> Mage::helper('catalog')->__('Attrib. Set Name'),
        //         'width' => '100px',
        //         'index' => 'attribute_set_id',
        //         'type'  => 'options',
        //         'options' => $sets,
        // ));

        $this->addColumn('sku',
            array(
                'header'=> Mage::helper('catalog')->__('SKU'),
                'width' => '80px',
                'index' => 'sku',
        ));

        $categorys = $zgb->getSubCategorys();

        $this->addColumn('category',
                array(
                    'header'=> Mage::helper('catalog')->__('分类'),
                    'width' => '100px',
                    'index' => 'category_id',
                    'type'  => 'options',
                    'options' => $categorys,
                    'renderer' => 'Silk_Zgb_Block_Renderer_Category',
                    'filter_condition_callback' => array($this, 'filterCategoryCallback')
        ));

        $store = $this->_getStore();
        $this->addColumn('price',
            array(
                'header'=> Mage::helper('catalog')->__('Price'),
                'type'  => 'price',
                'currency_code' => $store->getBaseCurrency()->getCode(),
                'index' => 'price',
        ));

        if (Mage::helper('catalog')->isModuleEnabled('Mage_CatalogInventory')) {
            $this->addColumn('qty',
                array(
                    'header'=> Mage::helper('catalog')->__('Qty'),
                    'width' => '100px',
                    'type'  => 'number',
                    'index' => 'qty',
            ));
        }

        $this->addColumn('visibility',
            array(
                'header'=> Mage::helper('catalog')->__('Visibility'),
                'width' => '70px',
                'index' => 'visibility',
                'type'  => 'options',
                'options' => Mage::getModel('catalog/product_visibility')->getOptionArray(),
        ));

        if($store && $store->getId())
        {
            $this->addColumn('status_at', array(
                'header' => Mage::helper('sales')->__('启用/禁用时间'),
                'index' => 'status_at',
                'filter_index'=>'status_at',
                'type' => 'datetime',
                'width' => '100px',
            ));
        }

        $this->addColumn('status',
            array(
                'header'=> Mage::helper('catalog')->__('Status'),
                'width' => '70px',
                'index' => 'status',
                'type'  => 'options',
                'options' => Mage::getSingleton('catalog/product_status')->getOptionArray(),
        ));

        if($store && $store->getId())
        {
            //=========================
            $options = array();
            $dealers = Mage::getModel('zgb/dealer')->toOptionArray();
            foreach($dealers as $dealer)
            {
                $options[$dealer['value']] = $dealer['label'];
            }
            $this->addColumn('dealer',
                array(
                    'header'=> Mage::helper('catalog')->__('经销商'),
                    'width' => '100px',
                    'index' => 'dealer_id',
                    'type'  => 'options',
                    'options' => $options,
            ));
        }

        if (!Mage::app()->isSingleStoreMode()) {
            $this->addColumn('websites',
                array(
                    'header'=> Mage::helper('catalog')->__('Websites'),
                    'width' => '100px',
                    'sortable'  => false,
                    'index'     => 'websites',
                    'type'      => 'options',
                    'options'   => Mage::getModel('core/website')->getCollection()->toOptionHash(),
            ));
        }

        $this->addColumn('action',
            array(
                'header'    => Mage::helper('catalog')->__('Action'),
                'width'     => '50px',
                'type'      => 'action',
                'getter'     => 'getId',
                'actions'   => array(
                    array(
                        'caption' => Mage::helper('catalog')->__('Edit'),
                        'url'     => array(
                            'base'=>'adminhtml/catalog_product/edit',
                            'params'=>array('store'=>$this->getRequest()->getParam('store'),'audit'=>1,'popup'=>1),
                            'popup'    => 1
                        ),
                        'onclick' => "window.open(this.href, 'action_window', 'resizable=1,scrollbars=1');return false;",
                        'field'   => 'id'
                    )
                ),
                'filter'    => false,
                'sortable'  => false,
                'index'     => 'stores',
        ));


        return parent::_prepareColumns();
    }

    public function filterCategoryCallback($collection, $column)
    {
        $value = $column->getFilter()->getValue();
        $_category = Mage::getModel('catalog/category')->load($value);
        $collection->addCategoryFilter($_category);
        
        return $collection;
    }

    protected function _prepareMassaction()
    {
        if((int)$this->getRequest()->getParam('store', 0))
        {
            $this->setMassactionIdField('entity_id');
            $this->getMassactionBlock()->setFormFieldName('product');

            $statuses = Mage::getSingleton('catalog/product_status')->getOptionArray();

            array_unshift($statuses, array('label'=>'', 'value'=>''));
            $this->getMassactionBlock()->addItem('status', array(
                 'label'=> Mage::helper('catalog')->__('商品审核'),
                 'url'  => $this->getUrl('*/*/massStatus', array('_current'=>true)),
                 'additional' => array(
                        'visibility' => array(
                             'name' => 'status',
                             'type' => 'select',
                             'class' => 'required-entry',
                             'label' => Mage::helper('catalog')->__('Status'),
                             'values' => $statuses
                         )
                 )
            ));

            // $statuses = Mage::getSingleton('catalog/product_visibility')->getOptionArray();

            // $visibilitys = array();
            // foreach($statuses as $key=>$val)
            // {
            //     $visibilitys[] = array('label'=>$val,'value'=>$key);
            // }
            // $this->getMassactionBlock()->addItem('status', array(
            //      'label'=> Mage::helper('catalog')->__('商品审核'),
            //      'url'  => $this->getUrl('*/*/massStatus', array('_current'=>true)),
            //      'additional' => array(
            //             'visibility' => array(
            //                  'name' => 'status',
            //                  'type' => 'select',
            //                  'class' => 'required-entry',
            //                  'label' => Mage::helper('catalog')->__('Status'),
            //                  'values' => $visibilitys
            //              )
            //      )
            // ));

            //if (Mage::getSingleton('admin/session')->isAllowed('catalog/update_attributes')){
            //    $this->getMassactionBlock()->addItem('attributes', array(
            //        'label' => Mage::helper('catalog')->__('Update Attributes'),
            //        'url'   => $this->getUrl('*/catalog_product_action_attribute/edit', array('_current'=>true))
            //    ));
            //}

            Mage::dispatchEvent('adminhtml_catalog_product_grid_prepare_massaction', array('block' => $this));
        }
        return $this;
    }

    public function getGridUrl()
    {
        return $this->getUrl('admin_zgb/adminhtml_audit/grid', array('_current'=>true));
    }

    public function getRowUrl($row)
    {
        return "";
        // return $this->getUrl('adminhtml/catalog_product/edit', array(
        //     'store'=>$this->getRequest()->getParam('store'),
        //     'audit'=>'1',
        //     'id'=>$row->getId())
        // );
    }
}
